<template>
  <!-- 电梯管理 -- 机构管理 -- 添加机构-->
  <div class="page-operate addOrganization">
    <!-- 位置模块 -->
    <HeadTop></HeadTop>
    <div class="page-head">
      <span class="operate-text">权限设置</span>
      <div class="operate-box">
        <button class="submit" style="margin-right: 10px" @click="changeOrganPower">确定修改</button>
        <button @click="back">返回</button>
        <!--<button>刷新</button>-->
      </div>
    </div>
    <div class="content-area">
      <div class="main-content form-edit perm-content">
        <!--content start-->
        <div class="perm-box">
          <div class="perm-box-head">
            <div>
              <p>
                <span class="sp-mgR5">机构名称:</span>
                <span class="sp-value">{{name}}</span>
              </p>
              <p>
                <span class="sp-mgR5">机构类型:</span>
                <span class="sp-value">{{organName}}</span>
              </p>
            </div>

          </div>
          <div class="form-box">
            <el-tree
              ref="tree"
              :data="userAuthorityTreeData"
              show-checkbox
              node-key="code"
              default-expand-all
              :default-checked-keys="userHasAuthority"
              :props="defaultProps">
            </el-tree>
          </div>
        </div>
        <!--content end-->
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss" type="text/scss">
  @import '../../../../style/entry/components/pageChildCommon';
  @import '../../../../style/entry/page/permission';
  .perm-box-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    button {
      width: 65px;
      height: 22px;
      border: solid 1px #E5701C;
      color: #E5701C;
      font-size: 12px;
      margin: 0 0 0 10px;
    }
  }
</style>
<script>
  import com from '../../../../js/common'
  import HeadTop from "../../../../components/head-top/head-top"
  import {getEditOrganPower, getOrganDetail, getOrganTypeList, updateOrganPower} from '@/api/getData'

  export default {
    components: {
      HeadTop
    },
    data() {
      return {
        userAuthorityTreeData: [],
        defaultProps: {
          children: 'list',
          label: 'name'
        },
        userHasAuthority: [],
        name: '',
        organName: '',
        organId: '',
        treeObj: []
      }
    },
    created() {
      this.organId = this.$route.query.organId
      this.getPageData()
    },
    methods: {
      // 获取页面所需数据
      getPageData() {
        this.getOrganPower()
        this.getOrganMsg()
      },
      // 获取机构权限信息
      getOrganPower() {
        const organId = this.$route.query.organId
        getEditOrganPower({
          id: organId
        }).then((pow) => {
          this.resolveUserAuthorityTree(pow.data.data)
        }).catch(err => this.$message.error(err.data.message))
      },
      // 获取机构信息
      getOrganMsg() {
        const organId = this.$route.query.organId
        getOrganDetail({
          id: organId
        }).then((msg) => {
          this.name = msg.data.data.name
          // 根据机构信息中的type获取机构类别
          this.getOrganLists(msg)

        }).catch(err => this.$message.error(err.data.message))
      },
      // 获取机构类型列表
      getOrganLists(msg) {
        getOrganTypeList({}).then((list) => {
          const arr = list.data.data
          arr.map((val) => {
            if (val.value === msg.data.data.type) {
              this.organName = val.key
            }
          })
        }).catch(err => this.$message.error(err.data.message))
      },
      // 解析成权限树
      resolveUserAuthorityTree(authorityArr) {
        let authorityArrObj = new Map()
        let authorityTreeArr = []
        let selectObj = {}
        authorityArr.map((currentValue) => {
          // 将当前code存储于map中
          let code = currentValue.code
          authorityArrObj[code] = currentValue
          // 根据code值长度为3时直接push,靠引用
          if (currentValue.code.length === 3) {
            authorityTreeArr.push(authorityArrObj[code])
          } else {
            let auth = currentValue.auth
            if (auth === "1") {
              selectObj[code] = code
            }
            let parentid = currentValue.code.substring(0, currentValue.code.length - 3)
            // 当存在父节点也被选中时,删除父组件
            if (selectObj[parentid]) {
              delete selectObj[parentid]
            }
            if (authorityArrObj[parentid].list) {
              authorityArrObj[parentid].list.push(currentValue)
            }
            else {
              authorityArrObj[parentid].list = []
              authorityArrObj[parentid].list.push(currentValue)
            }
          }
        })
        this.treeObj = authorityArrObj
        this.userAuthorityTreeData = authorityTreeArr
        this.userHasAuthority = Object.keys(selectObj)
      },
      // 修改当前权限
      changeOrganPower() {
        const param = {}
        param.id = this.organId
        param.auths = this.getBackstageNeedPower(this.$refs.tree.getCheckedKeys())
        updateOrganPower(param).then((res) => {
          com.mask()
          this.$message.success({
            message: '操作成功',
            duration: 1500,
            onClose: () => {
              com.unmask()
              this.$router.push('/manage/systemMgr/organMgr')
            }
          })
        }).catch((err) => {
          this.$message.error(err.data.message)
        })
      },

      // 解析当前权限,将当前权限的父权限找到

      getBackstageNeedPower(nowPower) {
        let obj = {}
        let check = true
        // 先拍好顺序,不然肯定找不到爸爸
        nowPower = nowPower.sort()
        nowPower.map((v) => {
          obj[v] = v
          if (v.length >= 6) {
            let parentid = v.substring(0, v.length - 3)
            // 如果当前数据遍历出来的时候存在父权限
            if (!obj[parentid]) {
              obj[parentid] = parentid
              check = false
            }
          }
        })
        // 最后一次遍历,数组中全拥有父组件
        if (check) {
          return Object.keys(obj).map((value) => {
            return this.treeObj[value].id
          })
        } else {
          return this.getBackstageNeedPower(Object.keys(obj))
        }
      },
      // 返回上页
      // 返回上一级
      back() {
        this.$router.go(-1);
        // 导航栏同时信息返回上级
      },
    }
  }
</script>
